package com.lsh.ofc.core.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.ofc.core.constant.Constants;
import com.lsh.ofc.core.entity.OfcCustomer;
import com.lsh.ofc.core.entity.OfcOrderHead;
import com.lsh.ofc.core.entity.OfcSoDetail;
import com.lsh.ofc.core.entity.OfcSoHead;
import com.lsh.ofc.core.enums.SoStatus;
import com.lsh.ofc.core.proxy.service.WumartBasicService;
import com.lsh.ofc.core.service.SupplierConfigService;
import com.lsh.ofc.core.util.OFCUtils;
import com.lsh.ofc.proxy.context.WumartBasicContext;
import com.lsh.ofc.proxy.model.CreateWgSoReqHead;
import com.lsh.ofc.proxy.model.CreateWgSoRespDetail;
import com.lsh.ofc.proxy.model.CreateWgSoRespHead;
import com.lsh.ofc.proxy.service.WgServiceProxy;
import com.lsh.ofc.proxy.util.MethodCallLogCollector;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【链商WG】创建SO处理Handler
 *
 * @author miaozhuang
 * @date 18/7/9
 */
public class CreateSoByWGHandler extends CreateSoHandler {

    private final WumartBasicService wumartBasicService;

    private final WgServiceProxy wgServiceProxy;

    private final SupplierConfigService supplierConfigService;

    protected CreateSoByWGHandler(final ApplicationContext context, final OfcOrderHead ofcOrderHead, final OfcSoHead so, final OfcCustomer customer) {
        super(context, ofcOrderHead, so, customer);
        this.wumartBasicService = context.getBean(WumartBasicService.class);
        this.wgServiceProxy = context.getBean(WgServiceProxy.class);
        this.supplierConfigService = context.getBean(SupplierConfigService.class);
    }

    @Override
    protected boolean process(final OfcSoHead so, final OfcCustomer customer) throws BusinessException {

        CreateWgSoRespHead createSoResp;
        try {
            MethodCallLogCollector.init();
            MethodCallLogCollector.business(so.getSoBillCode(), 10);

            String costomerId = this.wumartBasicService.getCostomerId(WumartBasicContext.buildContext(so.getRegionCode(), so.getSupplierCode(), so.getSupplierOrg(), so.getSupplierId(), so.getSupplierGroup()));
            String ownerId = this.wumartBasicService.getOwnerId(WumartBasicContext.buildContext(so.getRegionCode(), so.getSupplierCode(), so.getSupplierOrg(), so.getSupplierId(), so.getSupplierGroup()));
            String wgPath = this.wumartBasicService.getWmsPath(WumartBasicContext.buildContext(so.getRegionCode(), so.getSupplierCode(), so.getSupplierOrg(), so.getSupplierId(), so.getSupplierGroup()));

            String deliveryType = this.wumartBasicService.getDeliveryType(WumartBasicContext.buildContext(so.getRegionCode(), so.getSupplierCode(), so.getSupplierOrg(), so.getSupplierId(), so.getSupplierGroup()));
            String saleModel = this.wumartBasicService.getSaleModel(WumartBasicContext.buildContext(so.getRegionCode(), so.getSupplierCode(), so.getSupplierOrg(), so.getSupplierId(), so.getSupplierGroup()));
            if (deliveryType.equals("3") && saleModel.equals("2")) {

                ownerId = this.wgServiceProxy.getVenderIdInfo(wgPath, so.getVenderId(), so.getSupplierId());

                if(StringUtils.isBlank(ownerId)){
                    logger.info(so.getSoBillCode() + " 云仓获取ownerId 失败");
                    return false;
                }
            }

            CreateWgSoReqHead createSoReq = this.getCreateWgSoReq(costomerId, ownerId);
            createSoResp = this.wgServiceProxy.createSo(createSoReq, wgPath);

        } finally {
            MethodCallLogCollector.upload();
            MethodCallLogCollector.clear();
        }

        logger.info("*****CreateWgSoRespHead createSoResp is " + JSON.toJSONString(createSoResp));

        String supplySoCode = createSoResp.getSoId();
        Map<Integer, OfcSoDetail> detailMap = new HashMap<>();
        for (OfcSoDetail detail : so.getDetails()) {
            if (detail.getItemCode() == 0) {
                detailMap.put(detail.getItemNo(), detail);
            } else {
                detailMap.put(detail.getItemCode(), detail);
            }
        }
        logger.info("*****CreateWgSoRespHead detailMap is " + JSON.toJSONString(detailMap));

        List<OfcSoDetail> updateDetails = new ArrayList<>(detailMap.size());
        BigDecimal totalSkuQty = BigDecimal.ZERO;
        for (CreateWgSoRespDetail respDetail : createSoResp.getItems()) {

            OfcSoDetail detail = detailMap.get(Integer.valueOf(respDetail.getLineNo()));
            BigDecimal respQty = new BigDecimal(respDetail.getRealQty());
            if (respQty == null) {
                respQty = BigDecimal.ZERO;
            }
            detail.setSkuSupplyQty(respQty);

            OfcSoDetail updateDetail = new OfcSoDetail();
            updateDetail.setId(detail.getId());
            updateDetail.setSkuSupplyQty(respQty);
            updateDetails.add(updateDetail);
            totalSkuQty = totalSkuQty.add(respQty);
        }

        JSONObject ext = JSON.parseObject(so.getExt());
        ext.put(Constants.SO_H_REF_SO_CODE, supplySoCode);
        ext.put(Constants.SO_H_FULFILL_CREATE_TIME, OFCUtils.currentTime());
        OfcSoHead updateHead = new OfcSoHead();
        updateHead.setId(so.getId());
        updateHead.setSoBillCode(so.getSoBillCode());
        updateHead.setSoStatus(SoStatus.CREATED.getValue());
        updateHead.setSoCode(supplySoCode);
        updateHead.setWarehouseCode(so.getWarehouseCode());
        updateHead.setWarehouseName(so.getWarehouseName());
        updateHead.setTotalSkuSupplyQty(totalSkuQty);
        updateHead.setExt(ext.toJSONString());
        updateHead.setDetails(updateDetails);
        updateHead.setPushPsiFlag(so.getPushPsiFlag());
        logger.info("*****CreateWgSoRespHead update4Create");
        if (StringUtils.isBlank(so.getPushPsiFlag()) || so.getPushPsiFlag().equals("0")) {
            this.ofcSoService.update4Create(updateHead, SoStatus.UNCREATED, SoStatus.CREATED, so.getVenderId());
        } else {
            //TODO 临时处理  优化方式 脚本处理 2019-12-10
            OfcSoHead updateFilter = new OfcSoHead();
            updateFilter.setId(so.getId());
            OfcSoHead updateHeadPsi = new OfcSoHead();
            updateHeadPsi.setSoCode(supplySoCode);
            updateHeadPsi.setExt(ext.toJSONString());

            this.ofcSoService.updateByFilter(updateHeadPsi, updateFilter);
        }

        return true;
    }

}
